//
//  XBWebView.m
//  CallShow
//
//  Created by 胡锦涛 on 2018/4/23.
//  Copyright © 2018年 胡锦涛. All rights reserved.
//

#import "XBWebView.h"
#import <CommonCrypto/CommonDigest.h>
#import "XBProgressView.h"
#import "HKMacro.h"
#import "HKIdentify.h"
#import "HKConfig.h"
NSString *const JSObjectName = @"kf";
@interface XBWebView()
@property (nonatomic,strong) NSArray *cookies;
@end
@implementation XBWebView
- (instancetype)initWithFrame:(CGRect)frame delegate:(id <WKScriptMessageHandler, WKNavigationDelegate, WKUIDelegate>)delegate {
    
    for (UIView * v in self.subviews) {
        v.backgroundColor = [UIColor clearColor];
    }
    _delegate = delegate;
    UIWebView *webView = [[UIWebView alloc] initWithFrame:frame];
    NSString *userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    
    NSString *v = [NSString stringWithFormat:@"%@/%@",HKDisplayName,HKShortVersion];
    NSString *newUserAgent = userAgent;
    if (![userAgent containsString:v]) {
        newUserAgent = [NSString stringWithFormat:@"%@ %@",v,userAgent];
    }
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent",nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.processPool = [XBProgresspool sharedInstance];
    config.preferences = [[WKPreferences alloc] init];
    config.preferences.minimumFontSize = 10;
    config.preferences.javaScriptEnabled = YES;
    config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
    config.userContentController = [[WKUserContentController alloc] init];
    config.allowsInlineMediaPlayback = YES;
    if (@available(iOS 10.0, *)) {
        config.mediaTypesRequiringUserActionForPlayback = false;
    } else {
        // Fallback on earlier versions
    }
    if (IOS9_OR_LATER) {
        config.allowsAirPlayForMediaPlayback =YES;//airplay isallowed
        config.allowsPictureInPictureMediaPlayback = NO;
    }
    if (@available(iOS 10.0, *)) {
        config.ignoresViewportScaleLimits = NO;
    } else {
        // Fallback on earlier versions
    }
    if (@available(iOS 10.0, *)) {
        config.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeNone;
    } else {
        // Fallback on earlier versions
    }
    [config.userContentController addScriptMessageHandler:[[WeakScriptMessageDelegate alloc] initWithDelegate:delegate ] name:JSObjectName];
    //注入cookie
    WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource:[XBWebView cookiesForWebAdding] injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
    [config.userContentController addUserScript:cookieScript];

    NSError *error;
    NSString *source = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ios_brige" ofType:@"js"] encoding:NSUTF8StringEncoding error:&error];
    if (source) {
        NSString *replacedStr = [source stringByReplacingOccurrencesOfString:@"$headParams" withString:[delegate performSelector:@selector(getHeadParams)]];
        NSString *loginState;
        if ([[HKIdentify sharedInstance] userState]) {
            loginState = @"true";
        } else {
            loginState = @"false";
        }
        replacedStr = [replacedStr stringByReplacingOccurrencesOfString:@"$loginState" withString:loginState];
        WKUserScript *userScript = [[WKUserScript alloc] initWithSource:replacedStr injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
        [config.userContentController addUserScript:userScript];
    } else {
        NSLog(@"load brige js error %@", error.localizedDescription);
    }
//    NSString *cookieValue = @"document.cookie = 'XBSESSIONID=3acd2e95-55e8-4ddd-8444-aaf856f67cc7';document.cookie = 'channel=appstore';";
//    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"requestCookie"]) {
//        NSString* cookieStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"requestCookie"];
//        NSString* s = [NSString stringWithFormat:@"document.cookie = '%@;path=/';", cookieStr];
//        WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource:s injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
//        [config.userContentController addUserScript:cookieScript];
//        NSLog(@"addcookiescript----------------%@",cookieStr);
//    }
    return [self initWithFrame:frame configuration:config delegate:delegate];
}
#pragma mark - 添加注入的JS

- (void)addCookie{
    
    [self removeCookie];
    
    WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource:[XBWebView cookiesForWebAdding] injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
    [self.configuration.userContentController addUserScript:cookieScript];
    
    NSLog(@"------------sleepbegin---------");
    //    [NSThread sleepForTimeInterval:2];
    NSLog(@"------------sleepend---------");
}

- (void)removeCookie{
    
    NSMutableString *source = [NSMutableString string];
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:HK_SERVER_URL_PREFIX]];
    for (NSHTTPCookie *cookie in cookies)
    {
        [source appendFormat:@"document.cookie='%@=;",cookie.name];
        [source appendFormat:@"domain=%@;",cookie.domain];
        [source appendFormat:@"path=%@;",cookie.path];
        
        if (cookie.expiresDate)
        {
            NSDate * expiresDate = cookie.expiresDate;
            NSString *expires = [XBWebView stringbyFormatter:expiresDate];
            [source appendFormat:@"expires=%@';",expires];
        }else
        {
            [source appendFormat:@"';"];
        }
    }
    WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
    [self.configuration.userContentController addUserScript:cookieScript];
    
}

+ (NSString *)stringbyFormatter:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"EEE, dd-MMM-yy HH:mm:ss"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    [dateFormatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"en_US"]];
    NSString *dateString = [dateFormatter stringFromDate:date];
    return [dateString stringByAppendingString:@" GMT"];
}

+ (NSString *)cookiesForWebAdding
{
    NSMutableString *source = [NSMutableString string];
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:HK_SERVER_URL_PREFIX]];
    NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"expiresDate" ascending:NO];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:&sorter count:1];
    NSArray *sortedArray = [cookies sortedArrayUsingDescriptors:sortDescriptors];
    for (NSHTTPCookie *cookie in sortedArray)
    {
        if ([cookie.name isEqualToString:@"HKSESSIONID"]) {
            //NSString *name = cookie.name;
            //NSString *value = APPCookie;
            NSString *domain = cookie.domain;
            NSString *path = cookie.path;
            [source appendFormat:@"document.cookie='%@;",APPCookie];
            [source appendFormat:@"domain=%@;",domain];
            [source appendFormat:@"path=%@;",path];
            
            if (cookie.expiresDate)
            {
                NSDate * expiresDate = cookie.expiresDate;
                NSString *expires = [XBWebView stringbyFormatter:expiresDate];
                [source appendFormat:@"expires=%@';",expires];
            }
            else
            {
                [source appendFormat:@"';"];
            }
            break;
        }
    }
    return source;
}

- (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration delegate:(id <WKScriptMessageHandler, WKNavigationDelegate, WKUIDelegate>)delegate {
    if (self = [super initWithFrame:frame configuration:configuration]) {
        self.navigationDelegate = delegate;
        self.UIDelegate = delegate;
        self.allowsBackForwardNavigationGestures = YES;
        [self addObserver:delegate forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
        [self addObserver:delegate forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
        [self addObserver:delegate forKeyPath:@"loading" options:NSKeyValueObservingOptionNew context:nil];
        [self evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
            NSLog(@"%@", result);
        }];
    }
    return self;
}

- (void)showLoading {
    [[XBProgressView sharedInstance] addTo:self];
}

- (void)hideLoading {
    [XBProgressView dismiss];
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end

@implementation WeakScriptMessageDelegate

- (instancetype)initWithDelegate:(id <WKScriptMessageHandler>)scriptDelegate {
    self = [super init];
    if (self) {
        _scriptDelegate = scriptDelegate;
    }
    return self;
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    [self.scriptDelegate userContentController:userContentController didReceiveScriptMessage:message];
}
@end

@implementation XBProgresspool

+(instancetype)sharedInstance{
    static XBProgresspool *pool = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        pool = [[XBProgresspool alloc]init];
    });
    return pool;
}

@end
